<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="部门" prop="deptId">
        <el-select v-model="queryParams.deptId" placeholder="请选择部门" clearable @change="handleDeptChange">
          <el-option
            v-for="dept in deptOptions"
            :key="dept.deptId"
            :label="dept.deptName"
            :value="dept.deptId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="日期" prop="scheduleDate">
        <el-date-picker
          v-model="queryParams.scheduleDate"
          type="date"
          placeholder="选择日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['manage:schedule:add']"
        >新增排班</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-copy-document"
          size="mini"
          @click="handleCopyLastWeek"
          v-hasPermi="['manage:schedule:add']"
        >复制上周</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleClearCurrent"
          v-hasPermi="['manage:schedule:remove']"
        >清空当前</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['manage:schedule:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-check"
          size="mini"
          @click="handleSaveAll"
          v-hasPermi="['manage:schedule:edit']"
        >保存排班表</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getWeekSchedule"></right-toolbar>
    </el-row>

    <!-- 周导航 -->
    <div class="week-navigation">
      <el-button-group>
        <el-button size="small" @click="previousWeek">
          <i class="el-icon-arrow-left"></i> 上一周
        </el-button>
        <el-button size="small" disabled>
          {{ currentWeekText }}
        </el-button>
        <el-button size="small" @click="nextWeek">
          下一周 <i class="el-icon-arrow-right"></i>
        </el-button>
      </el-button-group>
    </div>

    <!-- 排班表格 -->
    <div class="schedule-table-container">
      <el-table
        :data="scheduleTableData"
        border
        style="width: 100%"
        :header-cell-style="{background:'#f5f7fa',color:'#606266'}"
        v-loading="loading"
      >
        <el-table-column prop="timeSlot" label="时间段" width="100" align="center" fixed="left" />
        <el-table-column
          v-for="day in weekDays"
          :key="day.date"
          :label="day.label"
          :prop="day.prop"
          align="center"
          min-width="150"
        >
          <template slot-scope="scope">
            <div class="schedule-cell" @click="handleCellClick(scope.row.timeSlot, day.date)">
              <div v-if="scope.row[day.prop] && scope.row[day.prop].length > 0">
                <div
                  v-for="(schedule, index) in scope.row[day.prop]"
                  :key="index"
                  class="schedule-item"
                >
                  <div class="employee-name">{{ schedule.employeeName }}</div>
                  <div class="window-info">窗口{{ schedule.windowNumber }}</div>
                </div>
              </div>
              <div v-else class="empty-cell">
                <i class="el-icon-plus"></i>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 新增/编辑排班对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="排班日期" prop="scheduleDate">
              <el-date-picker
                v-model="form.scheduleDate"
                type="date"
                placeholder="选择日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门" prop="deptId">
              <el-select v-model="form.deptId" placeholder="请选择部门" style="width: 100%" @change="handleFormDeptChange">
                <el-option
                  v-for="dept in deptOptions"
                  :key="dept.deptId"
                  :label="dept.deptName"
                  :value="dept.deptId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-time-picker
                v-model="form.startTime"
                format="HH:mm"
                value-format="HH:mm"
                placeholder="选择开始时间"
                style="width: 100%">
              </el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endTime">
              <el-time-picker
                v-model="form.endTime"
                format="HH:mm"
                value-format="HH:mm"
                placeholder="选择结束时间"
                style="width: 100%">
              </el-time-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="窗口" prop="windowId">
              <el-select v-model="form.windowId" placeholder="请选择窗口" style="width: 100%">
                <el-option
                  v-for="window in windowOptions"
                  :key="window.windowId"
                  :label="`窗口${window.windowNumber}`"
                  :value="window.windowId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="值班人员" prop="employeeId">
              <el-select v-model="form.employeeId" placeholder="请选择值班人员" style="width: 100%">
                <el-option
                  v-for="employee in employeeOptions"
                  :key="employee.employeeId"
                  :label="employee.employeeName"
                  :value="employee.employeeId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSchedule,
  getWeekSchedule,
  getSchedule,
  addSchedule,
  updateSchedule,
  delSchedule,
  batchSaveSchedule,
  copyLastWeekSchedule,
  clearCurrentSchedule,
  checkScheduleConflict,
  getAvailableEmployees,
  getWindowList,
  exportSchedule
} from "@/api/manage/schedule"
import { listDept } from "@/api/manage/dept"

export default {
  name: "Schedule",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 当前周的开始日期
      currentWeekStart: null,
      // 查询参数
      queryParams: {
        deptId: null,
        scheduleDate: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        scheduleDate: [
          { required: true, message: "排班日期不能为空", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "结束时间不能为空", trigger: "blur" }
        ],
        windowId: [
          { required: true, message: "窗口不能为空", trigger: "change" }
        ],
        employeeId: [
          { required: true, message: "值班人员不能为空", trigger: "change" }
        ]
      },
      // 部门选项
      deptOptions: [],
      // 员工选项
      employeeOptions: [],
      // 窗口选项
      windowOptions: [],
      // 排班表格数据
      scheduleTableData: [],
      // 周天数据
      weekDays: []
    }
  },
  computed: {
    // 当前周文本
    currentWeekText() {
      if (!this.currentWeekStart) return ''
      const start = new Date(this.currentWeekStart)
      const end = new Date(start)
      end.setDate(start.getDate() + 6)
      return `${this.formatDate(start)} - ${this.formatDate(end)}`
    }
  },
  created() {
    this.initCurrentWeek()
    this.getDeptList()
    this.getWindowList()
    this.getWeekSchedule()
  },
  methods: {
    // 初始化当前周
    initCurrentWeek() {
      const today = new Date()
      const dayOfWeek = today.getDay()
      const diff = today.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1)
      this.currentWeekStart = new Date(today.setDate(diff))
      this.generateWeekDays()
    },
    // 生成周天数据
    generateWeekDays() {
      this.weekDays = []
      const weekNames = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
      for (let i = 0; i < 7; i++) {
        const date = new Date(this.currentWeekStart)
        date.setDate(this.currentWeekStart.getDate() + i)
        const dateStr = this.formatDate(date)
        this.weekDays.push({
          date: dateStr,
          label: `${weekNames[i]}\n${dateStr}`,
          prop: `day${i + 1}`
        })
      }
    },
    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    // 上一周
    previousWeek() {
      this.currentWeekStart.setDate(this.currentWeekStart.getDate() - 7)
      this.generateWeekDays()
      this.getWeekSchedule()
    },
    // 下一周
    nextWeek() {
      this.currentWeekStart.setDate(this.currentWeekStart.getDate() + 7)
      this.generateWeekDays()
      this.getWeekSchedule()
    },
    // 查询周排班表
    getWeekSchedule() {
      this.loading = true
      const params = {
        startDate: this.formatDate(this.currentWeekStart)
      }
      // 只有当部门ID不为null时才添加部门参数
      if (this.queryParams.deptId) {
        params.deptId = this.queryParams.deptId
      }
      if (this.queryParams.scheduleDate) {
        params.scheduleDate = this.queryParams.scheduleDate
      }

      getWeekSchedule(params).then(response => {
        this.processScheduleData(response.data)
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 处理排班数据
    processScheduleData(data) {
      // 初始化表格数据
      this.scheduleTableData = [
        { timeSlot: '上午', day1: [], day2: [], day3: [], day4: [], day5: [], day6: [], day7: [] },
        { timeSlot: '下午', day1: [], day2: [], day3: [], day4: [], day5: [], day6: [], day7: [] }
      ]

      // 填充排班数据
      data.forEach(schedule => {
        const dayIndex = this.getDayIndex(schedule.scheduleDate)
        const timeSlot = this.getTimeSlot(schedule.startTime)
        if (dayIndex >= 0 && timeSlot >= 0) {
          this.scheduleTableData[timeSlot][`day${dayIndex + 1}`].push(schedule)
        }
      })
    },
    // 获取日期索引
    getDayIndex(date) {
      return this.weekDays.findIndex(day => day.date === date)
    },
    // 获取时间段索引
    getTimeSlot(time) {
      const hour = parseInt(time.split(':')[0])
      if (hour < 12) return 0 // 上午
      return 1 // 下午
    },
    // 获取部门列表
    getDeptList() {
      listDept().then(response => {
        this.deptOptions = response.rows
        // 默认选择第一个部门并加载员工
        if (this.deptOptions.length > 0) {
          this.queryParams.deptId = this.deptOptions[0].deptId
          this.getEmployeeList(this.deptOptions[0].deptId)
        }
      })
    },
    // 获取员工列表 - 修正参数传递方式
    getEmployeeList(deptId) {
      // 确保deptId不为null或undefined
      if (!deptId) {
        console.warn('部门ID为空，无法获取员工列表')
        this.employeeOptions = []
        return
      }

      console.log('正在获取部门ID为', deptId, '的员工列表')

      // 修正：使用params对象传递参数
      const params = {
        deptId: deptId
      }

      // 添加加载状态
      this.employeeOptions = []

      getAvailableEmployees(params).then(response => {
        console.log('获取到的员工数据:', response)
        console.log('响应状态码:', response.code)
        console.log('响应消息:', response.msg)

        // 检查响应数据结构
        if (response && response.data && Array.isArray(response.data)) {
          this.employeeOptions = response.data
          console.log('成功加载员工数量:', response.data.length)
        } else if (response && Array.isArray(response)) {
          this.employeeOptions = response
          console.log('成功加载员工数量:', response.length)
        } else {
          console.warn('员工数据格式异常:', response)
          this.employeeOptions = []
          this.$modal.msgWarning('该部门暂无可用员工')
        }
      }).catch(error => {
        console.error('获取员工列表失败:', error)
        this.employeeOptions = []
        this.$modal.msgError('获取员工列表失败: ' + (error.message || '网络错误'))
      })
    },
    // 获取窗口列表
    getWindowList() {
      getWindowList().then(response => {
        this.windowOptions = response.data
      })
    },
    // 搜索区域部门变更处理
    handleDeptChange(deptId) {
      console.log('部门选择变更，新的部门ID:', deptId)
      this.queryParams.deptId = deptId

      // 立即更新员工列表
      if (deptId) {
        console.log('正在根据新选择的部门加载员工...')
        this.getEmployeeList(deptId)
      } else {
        console.log('部门选择为空，清空员工列表')
        this.employeeOptions = []
      }

      // 重新加载排班数据
      this.getWeekSchedule()
    },
    // 表单区域部门变更处理
    handleFormDeptChange(deptId) {
      console.log('表单部门选择变更，新的部门ID:', deptId)
      this.form.deptId = deptId

      // 清空之前选择的员工
      this.form.employeeId = null

      // 立即更新员工列表
      if (deptId) {
        console.log('正在根据表单选择的部门加载员工...')
        this.getEmployeeList(deptId)
      } else {
        console.log('表单部门选择为空，清空员工列表')
        this.employeeOptions = []
      }
    },
    // 单元格点击事件
    handleCellClick(timeSlot, date) {
      this.reset()
      this.form.scheduleDate = date
      this.form.startTime = timeSlot === '上午' ? '09:00' : '14:00'
      this.form.endTime = timeSlot === '上午' ? '12:00' : '17:00'
      // 设置默认部门为当前查询的部门
      if (this.queryParams.deptId) {
        this.form.deptId = this.queryParams.deptId
        this.getEmployeeList(this.queryParams.deptId)
      }
      this.open = true
      this.title = "新增排班"
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        scheduleId: null,
        scheduleDate: null,
        startTime: null,
        endTime: null,
        windowId: null,
        employeeId: null,
        deptId: null,
        remark: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getWeekSchedule()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      // 重置后重新设置默认部门
      if (this.deptOptions.length > 0) {
        this.queryParams.deptId = this.deptOptions[0].deptId
        this.getEmployeeList(this.deptOptions[0].deptId)
      } else {
        this.queryParams.deptId = null
        this.employeeOptions = []
      }
      this.queryParams.scheduleDate = null
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      // 设置默认部门为当前查询的部门
      if (this.queryParams.deptId) {
        this.form.deptId = this.queryParams.deptId
        this.getEmployeeList(this.queryParams.deptId)
      }
      this.open = true
      this.title = "新增排班"
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 检查冲突
          checkScheduleConflict(this.form).then(response => {
            if (response.data.hasConflict) {
              this.$modal.msgError(response.data.message)
              return
            }

            if (this.form.scheduleId != null) {
              updateSchedule(this.form).then(response => {
                this.$modal.msgSuccess("修改成功")
                this.open = false
                this.getWeekSchedule()
              })
            } else {
              addSchedule(this.form).then(response => {
                this.$modal.msgSuccess("新增成功")
                this.open = false
                this.getWeekSchedule()
              })
            }
          })
        }
      })
    },
    /** 复制上周排班 */
    handleCopyLastWeek() {
      const params = {
        startDate: this.formatDate(this.currentWeekStart)
      }
      // 只有当部门ID存在时才添加部门参数
      if (this.queryParams.deptId) {
        params.deptId = this.queryParams.deptId
      }

      this.$modal.confirm('是否确认复制上周排班到当前周？').then(function() {
        return copyLastWeekSchedule(params)
      }).then(() => {
        this.getWeekSchedule()
        this.$modal.msgSuccess("复制成功")
      }).catch(() => {})
    },
    /** 清空当前排班 */
    handleClearCurrent() {
      const params = {
        startDate: this.formatDate(this.currentWeekStart)
      }
      // 只有当部门ID存在时才添加部门参数
      if (this.queryParams.deptId) {
        params.deptId = this.queryParams.deptId
      }

      this.$modal.confirm('是否确认清空当前周的所有排班？').then(function() {
        return clearCurrentSchedule(params)
      }).then(() => {
        this.getWeekSchedule()
        this.$modal.msgSuccess("清空成功")
      }).catch(() => {})
    },
    /** 保存排班表 */
    handleSaveAll() {
      const scheduleData = []
      this.scheduleTableData.forEach((row, timeIndex) => {
        this.weekDays.forEach((day, dayIndex) => {
          const dayData = row[`day${dayIndex + 1}`]
          if (dayData && dayData.length > 0) {
            scheduleData.push(...dayData)
          }
        })
      })

      batchSaveSchedule(scheduleData).then(response => {
        this.$modal.msgSuccess("保存成功")
        this.getWeekSchedule()
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const params = {
        startDate: this.formatDate(this.currentWeekStart)
      }
      // 只有当部门ID存在时才添加部门参数
      if (this.queryParams.deptId) {
        params.deptId = this.queryParams.deptId
      }
      if (this.queryParams.scheduleDate) {
        params.scheduleDate = this.queryParams.scheduleDate
      }

      this.download('manage/schedule/export', params, `schedule_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style scoped>
.week-navigation {
  margin: 20px 0;
  text-align: center;
}

.schedule-table-container {
  margin-top: 20px;
}

.schedule-cell {
  min-height: 80px;
  padding: 8px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.schedule-cell:hover {
  background-color: #f5f7fa;
}

.schedule-item {
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
  border-radius: 4px;
  padding: 4px 8px;
  margin-bottom: 4px;
  font-size: 12px;
}

.employee-name {
  font-weight: bold;
  color: #1890ff;
}

.window-info {
  color: #666;
  font-size: 11px;
}

.empty-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 60px;
  color: #ccc;
  font-size: 20px;
}

.empty-cell:hover {
  color: #1890ff;
}
</style>
